requirejs(['kindeditor.ex', 'plupload', 'art-template'], function (_, _, template) {
    var homeworkDetailContentKEditor;//学生的作业内容的KindEditor
    $(document).ready(function () {
        //加载KindEditor
        loadKEditor();
        //当页面加载时,根据页面类型处理
        onEditPageLoad(pageType, $('#editForm'));
        if (pageType && pageType == PAGE_TYPE.VIEW) {
            homeworkDetailContentKEditor.readonly(true);
        }
    });

    /**
     * 加载KindEditor
     */
    function loadKEditor(){
        ///**
        // * 老师布置的作业内容
        // */
        //KindEditor.create('#homeworkContent', {
        //    readonlyMode: true,
        //    items: []
        //});

        /**
         * 学生的作业内容
         */
        //不适用 KindEditor.ready(function (K) {} 方式,应为ready()方法是DOMContentLoaded事件触发的,但这时dom结构早就完成了
        // ,所以直接用KindEditor.create;异步加载也是用的是KindEditor.create方式
        homeworkDetailContentKEditor = KindEditor.create('#homeworkDetailContent', {
            items: [
                'source', '|', 'undo', 'redo', '|', 'print', '|', 'justifyleft', 'justifycenter', 'justifyright',
                'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
                'superscript', 'selectall', '|', 'fullscreen',
                //'/', //换行符
                'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
                'italic', 'underline', 'strikethrough', 'removeformat', '|', 'hr'
            ],
            afterBlur: function () {
                this.sync();//将编辑器的内容设置到原来的textarea控件里。
            }
        });
    }


    /**
     * 提交状态：0：未提交（草稿状态）、1：已提交
     */
    var COMMIT_STATUS = {
        NOT_COMMIT: 0,
        COMMITTED: 1
    };

    /**
     * 保存作业草稿
     */
    $("#editButton,#cancelCommitButton").click(function () {
        var isValid = $('#editForm').form('validate');
        if (isValid) {
            $('#commitStatus').val(COMMIT_STATUS.NOT_COMMIT);//未提交（草稿状态）
            $.ajax({
                type: "post",
                url: ctx + "/study/homeworkDetail/edit",
                data: $("#editForm").serialize(),
                dataType: "json",
                success: function (result) {
                    ajaxReturnWithMsg(result, function () {
                        window.location = ctx + '/study/homeworkDetail/page/edit?id=' + result.object.id;
                    }, function () {

                    },'保存成功','保存失败');
                },
                error: function () {
                    messagerFail('保存失败');
                }
            });
        }
    });

    /**
     * 提交作业
     */
    $("#commitButton").click(function () {
        var isValid = $('#editForm').form('validate');
        if (isValid) {
            $('#commitStatus').val(COMMIT_STATUS.COMMITTED);//已提交
            $.ajax({
                type: "post",
                url: ctx + "/study/homeworkDetail/edit",
                data: $("#editForm").serialize(),
                dataType: "json",
                success: function (result) {
                    ajaxReturnWithMsg(result, function () {
                        window.location = ctx + '/study/homeworkDetail/page/edit?id=' + result.object.id;
                    }, function () {

                    },'提交成功','提交失败');
                },
                error: function () {
                    messagerFail('提交失败');
                }
            });
        }
    });

    /**
     * 上传附件
     */
    var id = $('#id').val();
    var fileUploader = new plupload.Uploader({
        browse_button: 'selectFileButton',
        url: ctx + "/study/homeworkDetail/upload?id=" + id,
        filters: {
            max_file_size: '20mb'//,
            //mime_types: [
            //    {title: "Image files", extensions: "jpg,gif,png,bmp"}
            //]
        },
        init: {
            PostInit: function () {
            },
            //当文件添加到上传队列后触发
            FilesAdded: function (up, files) {
                var id = $('#id').val();
                if (id) {
                    fileUploader.start();
                } else {
                    messagerShow('提示', '请先保存');
                }
            },
            //当队列中的某一个文件上传完成后触发
            FileUploaded: function (fileUploader, file, responseObject) {
                var result = jQuery.parseJSON(responseObject.response);
                ajaxReturnWithMsg(result, function () {
                    var homeworkDetail = result.object;
                    var fileHtml = template("delFileTemplate", homeworkDetail);
                    $("#fileListDiv").html(fileHtml);
                }, function () {

                },null,'上传文件失败');
            },
            Error: function (up, err) {
                if(err.code == -600){
                    messagerFail('上传文件失败：文件大小超出限制，最大20M');
                }
            }
        }
    });

    fileUploader.init();//在实例对象上调用init()方法进行初始化

    $(document).on('click', '.js-delFile', function () {
        var homeworkDetailId = $(this).data('id');
        var _this = $(this);
        var data = {'id': homeworkDetailId};
        $.ajax({
            type: "post",
            url: ctx + "/study/homeworkDetail/deleteFile",
            data: data,
            dataType: "json",
            success: function (result) {
                ajaxReturnWithMsg(result, function () {
                    _this.parent().remove();
                }, function () {

                },'删除成功','删除失败');
            },
            error: function () {
                messagerFail('删除失败');
            }
        });
    });
});

